package com.huobao.yunying.activitys;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ViewInject;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huobao.yunying.adapters.Adapter_Shaixuan_Second;
import com.huobao.yunying.adapters.Adapter_shaixuan_Frist;
import com.huobao.yunying.base.HuobaoBaseActivity;
import com.huobao.yunying.entity.Shaixuan;
import com.huobao.yunying.entity.ShaixuanValue;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpConst;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.zhangying.R;

import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class Act_Shaixuan extends HuobaoBaseActivity implements OnClickListener, OnCheckedChangeListener {
	/*********************
	 * Intent 需传过来的值
	 *************************************/
	// 分类ID
	private String cate_id;
	// 搜索时的关键词
	private String keyword;
	// 渠道值
	private String genre;
	// 属性值（5:26）第一个是属性名称id，第二个是属性名称值id
	private String props;
	// 品牌名
	private String brand;
	// （min-max)
	private String price;

	/****************************************************************************/
	@ViewInject(R.id.listview)
	private ListView listview;
	private Adapter_shaixuan_Frist adapter_frist;
	private Adapter_Shaixuan_Second adapter_second;

	// 标题栏
	@ViewInject(R.id.tv_title)
	private TextView tv_title;
	// 确定按钮
	@ViewInject(R.id.tv_1)
	private TextView tv_quding;

	private int selectPos = 0;
	// 渠道
	private String SelectGenre;

	@ViewInject(R.id.radiogroup)
	private RadioGroup rg;

	@ViewInject(R.id.im_back)
	private ImageView im_back;

	@Override
	protected int getContentView() {
		// TODO Auto-generated method stub
		return R.layout.layout_shaixuan;
	}

	@Override
	protected String getTitleText() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void init() {
		rg.setOnCheckedChangeListener(this);
		tv_quding.setOnClickListener(this);
		im_back.setOnClickListener(this);
		getIntentData();
		mAbTitleBar.setVisibility(View.GONE);
		adapter_frist = new Adapter_shaixuan_Frist(context);
		listview.setAdapter(adapter_frist);
		listview.setOnItemClickListener(new ItmeClickImpl(true));
		adapter_second = new Adapter_Shaixuan_Second(context);
		getSelectData();
	}

	/**
	 * 获取筛选数据
	 */
	private void getSelectData() {
		Map<String, String> map = HttpUtil.getParams(HttpConst.FRIST_KEY, "search", HttpConst.SECOND_KEY, "props");
		if (TextUtils.isEmpty(cate_id) == false) {
			map.put("cate_id", cate_id);
		}
		if (TextUtils.isEmpty(keyword) == false) {
			map.put("keyword", keyword);
		}
		if (TextUtils.isEmpty(genre) == false) {
			map.put("genre", genre);
		}
		if (TextUtils.isEmpty(props) == false) {
			map.put("props", props);
		}
		if (TextUtils.isEmpty(brand) == false) {
			map.put("brand", brand);
		}
		if (TextUtils.isEmpty(price) == false) {
			map.put("price", price);
		}
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				JSONArray array = jsonObject.getJSONArray("retval");
				List<Shaixuan> list = new ArrayList<Shaixuan>();
				for (int i = 0; i < array.size(); i++) {
					JSONObject object = array.getJSONObject(i);
					int pid = object.getIntValue("pid");
					if (pid > -9) {
						Shaixuan shaixuan = new Shaixuan();
						shaixuan.name = object.getString("name");
						shaixuan.pid = object.getString("pid");
						List<ShaixuanValue> values = null;
						try {
							values = JSON.parseArray(object.getString("value"), ShaixuanValue.class);
						} catch (Exception e) {
						}
						shaixuan.value = values;
						list.add(shaixuan);
					} else {
						// -9渠道，-8分类，-7品牌，-6价格
						switch (pid) {
							case -9:
								break;
							case -8:
								break;
							case -7:
								break;
							case -6:
								break;
						}
					}
				}
				adapter_frist.addAll(list);
			}

			@Override
			public void onHttpError(String error) {
			}
		});
	}

	private void getIntentData() {
		Intent intent = getIntent();
		cate_id = intent.getStringExtra("cate_id");
		keyword = intent.getStringExtra("keyword");
		genre = intent.getStringExtra("genre");
		props = intent.getStringExtra("props");
		brand = intent.getStringExtra("brand");
		price = intent.getStringExtra("price");
	}

	public class ItmeClickImpl implements OnItemClickListener {

		private boolean frist;

		public ItmeClickImpl(boolean frist) {
			this.frist = frist;
		}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if (frist) {
				List<ShaixuanValue> list = adapter_frist.getItem(position).value;
				if (list == null || list.size() == 0) {
					Toast.makeText(context, "没有相关数据！", Toast.LENGTH_SHORT).show();
					return;
				}
				selectPos = position;
				listview.setAdapter(adapter_second);
				adapter_second.clear();
				adapter_second.addAll(adapter_frist.getItem(position).value);
				adapter_second.setSelect(adapter_frist.getItem(position).selectValue);
				listview.setOnItemClickListener(new ItmeClickImpl(false));
				tv_title.setText(adapter_frist.getItem(position).name);
//				rg.setVisibility(View.GONE);
			} else {
				for (ShaixuanValue value : adapter_second.getList()) {
					value.isSelect = false;
				}
				ShaixuanValue value = adapter_second.getItem(position);
				value.isSelect = !value.isSelect;
				adapter_second.notifyDataSetChanged();
			}
		}
	}

	private void onBackClick() {
		ListAdapter adapter = listview.getAdapter();
		if (adapter.equals(adapter_frist)) {
			finish();
		} else {
			tv_title.setText("");
			listview.setAdapter(adapter_frist);
			listview.setOnItemClickListener(new ItmeClickImpl(true));
//			rg.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onBackClick();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.tv_1:
				ListAdapter adapter = listview.getAdapter();
				if (adapter.equals(adapter_frist)) {
					Intent intent = new Intent();
					StringBuffer sb = new StringBuffer();
					if (SelectGenre != null)
						intent.putExtra("genre", SelectGenre);
					for (Shaixuan shaixuan : adapter_frist.getList()) {
						int pid = Integer.parseInt(shaixuan.pid);
						ShaixuanValue selectValue = shaixuan.selectValue;
						switch (pid) {
							case -9:
								break;
							case -8:
								if (selectValue != null)
									intent.putExtra("cate_id", selectValue.value);
								break;
							case -7:
								if (selectValue != null)
									intent.putExtra("brand", selectValue.value);
								break;
							case -6:
								if (selectValue != null)
									intent.putExtra("price", selectValue.value);
								break;
							default:
								if (selectValue != null)
									sb.append(selectValue.pid + ":" + selectValue.vid + ";");
								break;
						}
					}
					if (sb.toString().equals("") == false)
						intent.putExtra("props", sb.toString().substring(0, sb.toString().length() - 1));
					setResult(RESULT_OK, intent);
					finish();
				} else {
//				rg.setVisibility(View.VISIBLE);
					tv_title.setText("");
					listview.setAdapter(adapter_frist);
					listview.setOnItemClickListener(new ItmeClickImpl(true));
					for (ShaixuanValue value : adapter_second.getList()) {
						if (value.isSelect) {
							LogUtil.e(adapter_frist.getList().get(selectPos).name);
							adapter_frist.getList().get(selectPos).selectValue = value;
							break;
						}
					}
				}
				break;
			case R.id.im_back:
				onBackClick();
				break;
		}
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
			case R.id.tv_zhipi:
				SelectGenre = "1";
				break;
			case R.id.tv_liutongpin:
				SelectGenre = "2";
				break;
			case R.id.tv_dailipin:
				SelectGenre = "3";
				break;
		}
	}
}
